from rest_framework import serializers #序列化
from rest_framework.response import Response #回应 
from rest_framework.decorators import api_view  #装饰器
from blog.models import *
from django.contrib.auth import login
from rest_framework.decorators import authentication_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework import status
from django.shortcuts import render, redirect
from blog.views import GenNumber
from django.core.mail import EmailMultiAlternatives



class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','email','is_active','username','profile')
        depth = 1


class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('id','name','email','desc','avatar')


class AnswerSerializer(serializers.ModelSerializer):
    author = UserProfileSerializer()
    class Meta:
        model = Answer
        fields = ('id','author','content','like_counts','dislike_counts','comment_counts','createtime','answer_comment','answer_vote','question')
        depth = 2

class QuestionSerializer(serializers.ModelSerializer):
    question_answer = AnswerSerializer(many=True)
    class Meta:
        model = Question
        fields = ('author', 'title' ,'desc', 'topics', 'answer_counts', 'createtime', 'question_answer','question_vote')
        depth = 1


class CommentSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Comment
        fields = "__all__"
        depth = 1



class DetailSerializer(serializers.ModelSerializer):
    question_answer = AnswerSerializer(many=True)

    class Meta:
        model = Question
        fields = ('author', 'title' ,'desc', 'topics', 'answer_counts', 'createtime', 'question_answer')
        depth = 1


@api_view(['GET'])
def test_api(request, id):
    question = Question.objects.get(id=id)
    serializers = QuestionSerializer(question)
    return Response(serializers.data)


@api_view(['GET'])
def home_api(request,number):
    question = Answer.objects.all()
    serializers = AnswerSerializer(question[:int(number)], many=True)
    return Response(serializers.data, status=status.HTTP_200_OK)




@api_view(['GET'])
def answer_api(request, number):
    answer_list = Answer.objects.all()
    serializers = AnswerSerializer(answer_list[:int(number)], many=True)
    return Response(serializers.data, status=status.HTTP_200_OK)


@api_view(['GET'])
def detail_question_api(request,id):
    question = Question.objects.get(id=id)
    serializers = DetailSerializer(question)
    return Response(serializers.data, status=status.HTTP_200_OK)


@api_view(['GET'])
def detail_answer_api(request,id):
    answer_list = Answer.objects.filter(question_id=id)
    serializers = AnswerSerializer(answer_list, many=True)
    return Response(serializers.data, status=status.HTTP_200_OK)


@api_view(['GET'])
def comment_api(request,id):
    comment_list = Comment.objects.filter(answer_id=id)
    serializers = CommentSerializer(comment_list, many=True)
    return Response(serializers.data, status=status.HTTP_200_OK)


@api_view(['POST','GET'])
def new_comment_api(request):
    if not request.auth:
        body = {'error':'未授权的请求'}
        return Response(body, status=status.HTTP_400_BAD_REQUEST)
    
    if request.method == "POST":
        content = request.POST.get('content')
        answer = request.POST.get('answer_id')
        comment = Comment(author_id=request.user.profile.id, answer_id=answer, content=content)
        comment.save()
        comment_count = Comment.objects.filter(answer_id=answer).count()
        answer_object = Answer.objects.get(id=answer)  
        answer_object.comment_counts = comment_count
        answer_object.save()
        return Response({'msg':'OK'}, status=status.HTTP_200_OK)





@api_view(['POST'])
def vote(request):
    if not request.user.is_authenticated():
        return redirect(to='Login')
    votes = request.POST.get('vote')
    answer_id = request.POST.get('answer_id')
    user_id = request.user.profile.id
    vaild_list = ['like','dislike','normal']
    if votes not in vaild_list:
        return Response({'error':'Illegal data'}, status=status.HTTP_400_BAD_REQUEST)
    try:  #改票的逻辑
        ticket = Vote.objects.get(voter_id=user_id,answer_id=answer_id)
        ticket.vote = votes
        ticket.save()

    except: #新票
        new_ticket = Vote(voter_id=user_id, vote=votes, answer_id=answer_id)
        new_ticket.save()

    Like_the_sum_of_tickets = Vote.objects.filter(answer_id=answer_id, vote='like').count()
    disLike_the_sum_of_tickets = Vote.objects.filter(answer_id=answer_id, vote='dislike').count()
    print('目前喜欢的票为：%s票，不喜欢的票为：%s票,问题ID为：%s' % (Like_the_sum_of_tickets,disLike_the_sum_of_tickets,answer_id))
    answer_vote_count = Answer.objects.get(id=answer_id)
    answer_vote_count.like_counts = Like_the_sum_of_tickets
    answer_vote_count.dislike_counts = disLike_the_sum_of_tickets
    answer_vote_count.save()

    return Response({'msg':'OK'}, status=status.HTTP_200_OK)


@api_view(['POST','DELETE'])
def add_answer(request):
    if not request.auth:
        return Response({'msg':'请求非法'}, status=status.HTTP_400_BAD_REQUEST)

    if request.method == "POST":
        question_id = request.POST.get('question_id')
        content = request.POST.get('content')
        user = request.user.profile.id
        if len(content) == 0:
            return Response({'msg':'answer can not be null'},status=status.HTTP_400_BAD_REQUEST)
        
        try:
            answer = Answer.objects.get(question_id=question_id, author_id=user)
            answer.content = content
            answer.save()
        except:
            new_answer = Answer(question_id=question_id, author_id=user, content=content)
            new_answer.save()
            answer_count = Answer.objects.filter(question_id=question_id).count()
            question = Question.objects.get(id=question_id)
            question.answer_counts = answer_count
            question.save()
        return Response({'msg':'OK'}, status=status.HTTP_200_OK)



@api_view(['POST'])
def add_question(request):
    title = request.POST.get('title')
    desc = request.POST.get('desc')
    topics = request.POST.get('topic').split()
    author = request.user.profile.id
    question = Question.objects.create(author_id=author, title=title, desc=desc)
    question.save()
    for topic in topics:
        if topic:
            try:
                t = Topic.objects.get(name=topic)
            except Exception:
                t = Topic(name=topic)
                t.save()
            question.topics.add(t)
    return Response({'msg':'OK'}, status=status.HTTP_200_OK)



@api_view(['DELETE'])
def delete_answer(request,id):
    if request.method == "DELETE":
        user_id = request.user.profile.id
        try:
            answer = Answer.objects.get(author_id=user_id, id=id)
            answer.delete()
            return Response({'msg':'ok'}, status=status.HTTP_200_OK)
        except:
            return Response({'msg':'请求非法'},status=status.HTTP_400_BAD_REQUEST)




@api_view(['POST'])
def send_captcha_email(request):
    email = request.POST.get('email')
    try:
        user = User.objects.get(email=email)
        code = GenNumber(4)
        subject = '你此次重置密码的验证码是:%s' % code
        text_content = ''
        html_content = '''
<tbody><tr>
<td bgcolor="#0373d6" height="54" align="center" style="border-top-left-radius:3px;border-top-right-radius:3px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr>
<td align="center" class="zhwd-high-res-img-wrap zhwd-zhihu-logo"><a href="http://tmail.zhihu.com/t?u=aHR0cDovL3d3dy56aGlodS5jb20vP3V0bV9jYW1wYWlnbj1lbWFpbF9yZXF1ZXN0JnV0bV9zb3VyY2U9dHJpZ2dlci1lbWFpbCZ1dG1fbWVkaXVtPWVtYWls&amp;i=1280818473&amp;l=zhihu&amp;s=0&amp;c=aT0xMjgwODE4NDczJmw9emhpaHUmcz0w" target="_blank"><img src="http://s1.zhimg.com/edm/s105/zhihu.png" width="71" height="54" style="outline:none; display:block; border:none; font-size:14px; font-family:Hiragino Sans GB; color:#ffffff;"></a>
</td>
</tr>
</tbody></table>
</td>
</tr>
<tr>
<td bgcolor="#ffffff" align="center" style="padding: 0 15px 0px 15px;">
<table border="0" cellpadding="0" cellspacing="0" width="480" class="responsive-table">
<tbody><tr>
<td>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td>
<table cellpadding="0" cellspacing="0" border="0" align="left" class="responsive-table">
<tbody><tr>
<td width="550" align="left" valign="top">
<table width="100%" border="0" cellpadding="0" cellspacing="0">

<tbody><tr>
<td bgcolor="#ffffff" align="left" style="background-color:#ffffff; font-size: 17px; color:#7b7b7b; padding:28px 0 0 0;line-height:25px;"><b>{}，你好，</b>
</td>
</tr>
<tr>
<td align="left" valign="top" style="font-size:14px; color:#7b7b7b; line-height: 25px; font-family:Hiragino Sans GB; padding: 20px 0px 20px 0px">你此次重置密码的验证码如下，请在 30 分钟内输入验证码进行下一步操作。 如非你本人操作，请忽略此邮件。
</td>
</tr>
<tr>
<td style="border-bottom:1px #f1f4f6 solid; padding: 0 0 40px 0;" align="center" class="padding">
<table border="0" cellspacing="0" cellpadding="0" class="responsive-table">
<tbody><tr>
<td>
<span style="font-family:Hiragino Sans GB;"><div style="padding:10px 18px 10px 18px;border-radius:3px;text-align:center;text-decoration:none;background-color:#ecf4fb;color:#4581E9;font-size:20px; font-weight:700; letter-spacing:2px; margin:0;white-space:nowrap"><span style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;" t="7" onclick="return false;">{}</span>
</div>
</span>
</td>
</tr>
</tbody></table>
</td>
</tr>

</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>

        '''.format(user.profile.name, code)

        msg = EmailMultiAlternatives(subject, text_content, 'ysmlfx@163.com', [email])
        
        msg.attach_alternative(html_content, "text/html") #发送html邮件
        msg.send()
        return Response({'msg':'ok'}, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        return Response({'msg':'请求非法'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)